package com.shanglv.web.common.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class BlockDirective extends BaseDirective implements TemplateDirectiveModel {

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String nameValue = getParams(params, ATTR_NAME);
        TemplateBodyModel newBody = (TemplateBodyModel)env.getVariable(OverrideDirective.OVERRIDE_VAR_PREFIX + nameValue);
        if (null == newBody ) {
            if (null != body) {
                body.render(env.getOut());
            }
        }else{
            TemplateDirectiveBody childNewBody = newBody.getChildNewBody();
            Writer out = env.getOut();
            if (newBody.isNeedAppend() && null != body) {
                body.render(out);
            }
            if (null != childNewBody) {
                childNewBody.render(out);
            }
        }
    }
}
